package com.ipay.core;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class WechatMessagePacker {
	private Logger logger=LoggerFactory.getLogger(getClass());
	
	public Map<String, String> unpack(String str) {
		Map<String, String> ret = new HashMap<String, String>();
		SAXBuilder sax = new SAXBuilder(false);
		InputStream in = null;
		Document doc = null;
		try {
			in = new ByteArrayInputStream(str.getBytes("utf-8"));
			doc = sax.build(in);
			Element eles = doc.getRootElement();
			for (Object e : eles.getChildren()) {
				if(!(e instanceof Element)) continue;
				Element ele = (Element) e;
				ret.put(ele.getName(), ele.getTextTrim());
			}
		} catch (JDOMException e) {
			logger.error("解包出错", e);
		} catch (IOException e) {
			logger.error("解包出错", e);
		}finally {
			try {
				if(in!=null) {
					in.close();
				}
			} catch (IOException e) {
				logger.error("解包出错", e);
			}
		}
		
		return ret;
	}
}
